import 'dart:typed_data';

import 'package:bluetooth_protocols_plugin/src/base/statistics/statistics_total_data_base.dart';
import 'package:bluetooth_protocols_plugin/src/tools/utils.dart';

/*
  typedef struct{        //24 bytes
    uint32_t mileage;              //总里程           单位 0.01km
    uint32_t consumption;          //总消耗能量       单位 0.01kJ
    uint32_t recovery;             //总回收能量       单位 0.01kJ
    uint32_t ride_time;            //总骑行时间       单位 S
    uint32_t power_on_time;        //总开机时间       单位 S
    uint32_t reserve;              //保留
  }VX_STATISTICS;
*/

// 统计总数据基类
abstract class LorinStatisticsTotalData extends StatisticsTotalDataBase {
  int mileage = 0; // 总里程，单位 0.01km
  int consumption = 0; // 总消耗能量，单位 0.01kJ
  int recovery = 0; // 总回收能量，单位 0.01kJ
  int rideTime = 0; // 总骑行时间，单位 S
  int powerOnTime = 0; // 总开机时间，单位 S

  // 从字节数据解析
  LorinStatisticsTotalData.fromBytes(Uint8List bytes) : super.fromBytes(bytes) {
    if (bytes.length < minLength) {
      throw ArgumentError(
          '字节数组长度不足，无法解析 $runtimeType，期望长度至少为 $minLength，实际长度为 ${bytes.length}');
    }
    var byteData = ByteData.sublistView(bytes);
    mileage = byteData.getUint32(0, Endian.little);
    consumption = byteData.getUint32(4, Endian.little);
    recovery = byteData.getUint32(8, Endian.little);
    rideTime = byteData.getUint32(12, Endian.little);
    powerOnTime = byteData.getUint32(16, Endian.little);
  }

  // 可选：添加一个方法来将对象转换为Map，方便序列化
  @override
  Map<String, dynamic> toMap() {
    return {
      'total_mileage': mileage,
      'total_consumption': consumption,
      'total_recovery': recovery,
      'total_ride_time': rideTime,
      'total_power_on_time': powerOnTime,
    };
  }

  @override
  int dataIntValue() {
    return Utils.computeDataIntVal(toBytes());
  }

  @override
  int dataLength() {
    return toBytes().length;
  }

  @override
  int get minLength => 24;

  @override
  Uint8List toBytes() {
    var byteData = ByteData(minLength);
    byteData.setUint32(0, mileage, Endian.little);
    byteData.setUint32(4, consumption, Endian.little);
    byteData.setUint32(8, recovery, Endian.little);
    byteData.setUint32(12, rideTime, Endian.little);
    byteData.setUint32(16, powerOnTime, Endian.little);
    return byteData.buffer.asUint8List();
  }
}
